<template>
  <div class="user-management">
    <!-- 搜索和操作区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入手机号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="用户等级">
          <el-select v-model="searchForm.level" placeholder="请选择等级" clearable style="width: 120px">
            <el-option label="普通用户" :value="1" />
            <el-option label="VIP用户" :value="2" />
            <el-option label="企业用户" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="注册时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
          <el-button type="success" :icon="Download" @click="handleExport">导出数据</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="12" :sm="6" v-for="stat in userStats" :key="stat.title">
        <el-card class="stat-card" :class="stat.type">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon :size="24"><component :is="stat.icon" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-title">{{ stat.title }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column label="用户信息" min-width="200">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="40" :src="row.avatar" />
              <div class="user-details">
                <div class="username">{{ row.username }}</div>
                <div class="user-id">ID: {{ row.id }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="130" />
        <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
        <el-table-column label="等级" width="100">
          <template #default="{ row }">
            <el-tag :type="getLevelTagType(row.level)">
              {{ getLevelText(row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="balance" label="余额" width="100">
          <template #default="{ row }">
            <span class="balance">¥{{ row.balance || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="registerTime" label="注册时间" width="160" />
        <el-table-column prop="lastLoginTime" label="最后登录" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetail(row)">
              详情
            </el-button>
            <el-dropdown @command="(command) => handleAction(command, row)">
              <el-button size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="editLevel">修改等级</el-dropdown-item>
                  <el-dropdown-item command="toggleStatus">
                    {{ row.status === 1 ? '禁用用户' : '启用用户' }}
                  </el-dropdown-item>
                  <el-dropdown-item command="resetPassword">重置密码</el-dropdown-item>
                  <el-dropdown-item command="viewOrders">查看订单</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户详情对话框 -->
    <UserDetail
      v-model:visible="detailVisible"
      :user-id="currentUserId"
    />

    <!-- 修改等级对话框 -->
    <el-dialog
      v-model="levelVisible"
      title="修改用户等级"
      width="400px"
    >
      <el-form :model="levelForm" label-width="80px">
        <el-form-item label="用户">
          <span>{{ currentUser?.username }}</span>
        </el-form-item>
        <el-form-item label="当前等级">
          <el-tag :type="getLevelTagType(currentUser?.level)">
            {{ getLevelText(currentUser?.level) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新等级">
          <el-select v-model="levelForm.level" style="width: 100%">
            <el-option label="普通用户" :value="1" />
            <el-option label="VIP用户" :value="2" />
            <el-option label="企业用户" :value="3" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="levelVisible = false">取消</el-button>
        <el-button type="primary" :loading="levelLoading" @click="handleUpdateLevel">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Download, ArrowDown } from '@element-plus/icons-vue'
import { userAPI } from '@/api/user'
import UserDetail from './components/UserDetail.vue'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])

const searchForm = reactive({
  username: '',
  phone: '',
  level: null,
  status: null,
  dateRange: []
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 用户统计数据
const userStats = [
  { title: '总用户数', value: '0', icon: 'User', type: 'primary' },
  { title: '活跃用户', value: '0', icon: 'UserFilled', type: 'success' },
  { title: '新增用户', value: '0', icon: 'Plus', type: 'warning' },
  { title: '禁用用户', value: '0', icon: 'UserFilled', type: 'danger' }
]

// 对话框状态
const detailVisible = ref(false)
const levelVisible = ref(false)
const levelLoading = ref(false)
const currentUserId = ref(null)
const currentUser = ref(null)

const levelForm = reactive({
  level: 1
})

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      size: pagination.size,
      username: searchForm.username || undefined,
      phone: searchForm.phone || undefined,
      level: searchForm.level !== null ? searchForm.level : undefined,
      status: searchForm.status !== null ? searchForm.status : undefined
    }

    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startTime = searchForm.dateRange[0]
      params.endTime = searchForm.dateRange[1]
    }

    const response = await userAPI.getList(params)
    tableData.value = response.data.records || []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取用户统计
const fetchUserStats = async () => {
  try {
    const response = await userAPI.getStats()
    const stats = response.data || {}
    userStats[0].value = stats.totalUsers || '0'
    userStats[1].value = stats.activeUsers || '0'
    userStats[2].value = stats.newUsers || '0'
    userStats[3].value = stats.disabledUsers || '0'
  } catch (error) {
    console.error('获取用户统计失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchUserList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    phone: '',
    level: null,
    status: null,
    dateRange: []
  })
  pagination.current = 1
  fetchUserList()
}

// 导出数据
const handleExport = async () => {
  try {
    ElMessage.info('导出功能开发中...')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 查看详情
const handleViewDetail = (row) => {
  currentUserId.value = row.id
  detailVisible.value = true
}

// 处理操作
const handleAction = async (command, row) => {
  currentUser.value = row

  switch (command) {
    case 'editLevel':
      levelForm.level = row.level
      levelVisible.value = true
      break
    case 'toggleStatus':
      await handleToggleStatus(row)
      break
    case 'resetPassword':
      await handleResetPassword(row)
      break
    case 'viewOrders':
      ElMessage.info('查看订单功能开发中...')
      break
  }
}

// 切换用户状态
const handleToggleStatus = async (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '启用' : '禁用'

  try {
    await ElMessageBox.confirm(
      `确定要${statusText}用户「${row.username}」吗？`,
      `${statusText}确认`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await userAPI.updateStatus(row.id, newStatus)
    ElMessage.success(`${statusText}成功`)
    fetchUserList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${statusText}用户失败:`, error)
      ElMessage.error(`${statusText}失败`)
    }
  }
}

// 重置密码
const handleResetPassword = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要重置用户「${row.username}」的密码吗？`,
      '重置密码',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    ElMessage.success('密码重置成功，新密码已发送至用户手机')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置密码失败:', error)
      ElMessage.error('重置密码失败')
    }
  }
}

// 更新用户等级
const handleUpdateLevel = async () => {
  if (!currentUser.value) return

  try {
    levelLoading.value = true
    await userAPI.updateLevel(currentUser.value.id, levelForm.level)
    ElMessage.success('等级更新成功')
    levelVisible.value = false
    fetchUserList()
  } catch (error) {
    console.error('更新等级失败:', error)
    ElMessage.error('更新等级失败')
  } finally {
    levelLoading.value = false
  }
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  fetchUserList()
}

// 当前页变化
const handleCurrentChange = (current) => {
  pagination.current = current
  fetchUserList()
}

// 获取等级文字
const getLevelText = (level) => {
  const levelMap = {
    1: '普通用户',
    2: 'VIP用户',
    3: '企业用户'
  }
  return levelMap[level] || '未知'
}

// 获取等级标签类型
const getLevelTagType = (level) => {
  const typeMap = {
    1: '',
    2: 'success',
    3: 'warning'
  }
  return typeMap[level] || ''
}

// 初始化
onMounted(() => {
  fetchUserList()
  fetchUserStats()
})
</script>

<style lang="scss" scoped>
.user-management {
  .search-card {
    margin-bottom: 20px;
  }

  .stats-row {
    margin-bottom: 20px;
  }

  .stat-card {
    position: relative;
    overflow: hidden;

    &.primary {
      border-left: 4px solid #409eff;
    }

    &.success {
      border-left: 4px solid #67c23a;
    }

    &.warning {
      border-left: 4px solid #e6a23c;
    }

    &.danger {
      border-left: 4px solid #f56c6c;
    }

    .stat-content {
      display: flex;
      align-items: center;

      .stat-icon {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;

        .el-icon {
          color: #fff;
        }
      }

      .stat-info {
        flex: 1;

        .stat-value {
          font-size: 20px;
          font-weight: 600;
          color: #2c3e50;
          line-height: 1;
          margin-bottom: 4px;
        }

        .stat-title {
          font-size: 14px;
          color: #909399;
        }
      }
    }

    &.primary .stat-icon {
      background: linear-gradient(135deg, #409eff, #66b1ff);
    }

    &.success .stat-icon {
      background: linear-gradient(135deg, #67c23a, #85ce61);
    }

    &.warning .stat-icon {
      background: linear-gradient(135deg, #e6a23c, #ebb563);
    }

    &.danger .stat-icon {
      background: linear-gradient(135deg, #f56c6c, #f78989);
    }
  }

  .table-card {
    .user-info {
      display: flex;
      align-items: center;

      .user-details {
        margin-left: 12px;

        .username {
          font-size: 14px;
          font-weight: 500;
          color: #2c3e50;
          margin-bottom: 2px;
        }

        .user-id {
          font-size: 12px;
          color: #909399;
        }
      }
    }

    .balance {
      font-weight: 500;
      color: #67c23a;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
}
</style>